const app = getApp()

Page({
  data: {
    isRegister: false,
    username: '',
    password: '',
    name: '',
    roomNumber: '',
    phone: ''
  },

  onLoad() {
    // 初始化云开发
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
  },

  // 切换到注册页面
  switchToRegister() {
    this.setData({
      isRegister: true,
      username: '',
      password: '',
      name: '',
      roomNumber: '',
      phone: ''
    })
  },

  // 切换到登录页面
  switchToLogin() {
    this.setData({
      isRegister: false,
      username: '',
      password: ''
    })
  },

  // 处理登录
  async handleLogin() {
    const { username, password } = this.data
    if (!username || !password) {
      wx.showToast({
        title: '请填写用户名和密码',
        icon: 'none'
      })
      return
    }

    try {
      // 调用云函数登录
      const { result } = await wx.cloud.callFunction({
        name: 'login',
        data: {
          username,
          password
        }
      })

      if (result.success) {
        // 保存用户信息
        app.saveUserInfo(result.userInfo)
        
        // 根据用户角色跳转到不同页面
        const rolePages = {
          owner: '/pages/owner/index/index',
          admin: '/pages/admin/index/index',
          security: '/pages/security/index/index'
        }
        
        wx.redirectTo({
          url: rolePages[result.userInfo.role]
        })
      } else {
        wx.showToast({
          title: result.message || '登录失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('登录失败', error)
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      })
    }
  },

  // 处理注册
  async handleRegister() {
    const { username, password, name, roomNumber, phone } = this.data
    
    // 验证输入
    if (!username || !password || !name || !roomNumber || !phone) {
      wx.showToast({
        title: '请填写所有信息',
        icon: 'none'
      })
      return
    }

    if (!/^1\d{10}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }

    try {
      // 调用云函数注册
      const { result } = await wx.cloud.callFunction({
        name: 'register',
        data: {
          username,
          password,
          name,
          roomNumber,
          phone
        }
      })

      if (result.success) {
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        })
        // 注册成功后切换到登录页面
        setTimeout(() => {
          this.switchToLogin()
        }, 1500)
      } else {
        wx.showToast({
          title: result.message || '注册失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('注册失败', error)
      wx.showToast({
        title: '注册失败，请重试',
        icon: 'none'
      })
    }
  }
}) 